package com.yb.xczx.cloud.auth.generator;

import com.yb.xczx.cloud.auth.bean.XczxOauth2AccessToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;

import java.time.Instant;
import java.util.UUID;

@Slf4j
public class XczxOAuth2AccessTokenGenerator implements OAuth2TokenGenerator<XczxOauth2AccessToken> {

	@Nullable
	public XczxOauth2AccessToken generate(OAuth2TokenContext context){
		if (!OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())
			||
			!context.getRegisteredClient().getTokenSettings().getAccessTokenFormat().equals(OAuth2TokenFormat.REFERENCE)) {
			return null;

		}
		String accessToken = UUID.randomUUID().toString().replace("-","");

		log.info("accessToken:{}",accessToken);
		Instant issuedAt = Instant.now();
		Instant expiresAt = issuedAt.plus(context.getRegisteredClient().getTokenSettings().getAccessTokenTimeToLive());
		XczxOauth2AccessToken oauth2AccessToken = new XczxOauth2AccessToken(accessToken, issuedAt, expiresAt);
		return oauth2AccessToken;
	}

}
